package com.yaodian100.ec.cobranding.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.FastDateFormat;
import org.springframework.transaction.annotation.Transactional;

import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.exception.CoreException;
import com.yaodian100.core.common.service.impl.DomainServiceImpl;
import com.yaodian100.core.common.utils.DateUtil;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.core.mail.entity.Mail;
import com.yaodian100.core.mail.service.MailService;
import com.yaodian100.core.sms.service.SmsService;
import com.yaodian100.core.template.service.TemplateService;
import com.yaodian100.ec.cobranding.entity.DPNStore;
import com.yaodian100.ec.cobranding.service.DPNService;
import com.yaodian100.ec.common.EcConstant;
import com.yaodian100.ec.common.EnvParameters;
import com.yaodian100.ec.coupon.entity.Coupon3rd;
import com.yaodian100.ec.coupon.entity.Coupon3rdItem;
import com.yaodian100.ec.coupon.service.Coupon3rdService;
import com.yaodian100.ec.member.entity.Member;
import com.yaodian100.ec.member.service.MemberService;
import com.yaodian100.ec.order.entity.OrderProduct;
import com.yaodian100.ec.order.entity.OrderProductDetail;
import com.yaodian100.ec.order.entity.Orders;
import com.yaodian100.ec.order.entity.ServiceOrders;

public class DPNServiceImpl extends DomainServiceImpl<DPNStore> implements DPNService {

	@Resource
	private TemplateService velocityService;
	@Resource
	private MailService mailService;
	@Resource
	private MemberService memberService;
	@Resource
	private SmsService smsService;
	@Resource
	private EnvParameters envParameters;
	@Resource
	private Coupon3rdService coupon3rdService;

	public List<DPNStore> getDPNStoretList(CommonCriteria crit) throws CoreException {
		String sortOrder[] = { "id asc" };
		List<DPNStore> DPNStores = getDao().getList(crit, sortOrder);
		return DPNStores;
	}
	
	@Transactional(readOnly = false)
	public void sendNotice(String velocityTemplate, Orders order,ServiceOrders so) throws CoreException {
		try {
			Member member = memberService.get(order.getMemberId());

			Map<String, Object> contentMap = new HashMap<String, Object>();

			logger.info("sendApplyClaimMail_orderId:", order.getOrderId());
			List<OrderProductDetail> getOrderProdDetailList = new ArrayList();
			for (OrderProduct op : order.getOrderProduct()) {
				getOrderProdDetailList.addAll(op.getOrderProductDetail());
			}
			SimpleDateFormat df = new SimpleDateFormat("yyyy/M/d");
			Calendar logisticFinalDt7 = DateUtil.getTargetDateAddDays(7, order.getLogisticFinalDt());
			CommonCriteria cc = new CommonCriteria();
			cc.addEq("storeId", order.getStoreId());
			DPNStore dpnStore = getDPNStoretList(cc).get(0);

			// order.setReceiverTp("30");
			contentMap.put("order", order);
			contentMap.put("dpnStore", dpnStore);
			contentMap.put("orderDt", FastDateFormat.getInstance(EcConstant.PATTERN_TIMESTAMP).format(order.getOrderDt()));
			contentMap.put("logisticFinalDt7", FastDateFormat.getInstance(EcConstant.PATTERN_DATE).format(logisticFinalDt7));
			contentMap.put("orderdetails", getOrderProdDetailList);
			contentMap.put("customerFax", ServerValue.getCustomerFax());
			contentMap.put("customerTel", ServerValue.getCustomerTel());
			contentMap.put("contextpath", ServerValue.getFrontContextPath());
			contentMap.put("basehref", "http://" + order.getDomainSrc());
			Mail mail = velocityService.formatToMail(velocityTemplate, contentMap);
			mail.setTo(member.getSendEmail());
			mail.setFrom(envParameters.getEmailFromSystem());

			// 以抵達店面
			if ("order.arriveStore".equals(velocityTemplate)) {
				Coupon3rd coupon = coupon3rdService.getActive(order);
				if (coupon != null && StringUtils.isNotBlank(coupon.getTemplateSMS())) {
					Coupon3rdItem couponItem = coupon3rdService.regCoupon(coupon, order);
					if (couponItem != null) {
						Map objs = new HashMap();
						objs.putAll(contentMap);
						objs.put("coupon", coupon);
						objs.put("couponItem", couponItem);
						String sms = velocityService.formatByStringTemplate(coupon.getTemplateSMS(), objs);
						smsService.sendSms(order.getReceiverMobile(), sms, order.getOrderId());
					}
				}

				mail.setSubject("商品已到店，请尽速前往达芙妮门店取货！");
				String msg = "您的耀点100商品已送至[达芙妮-" + dpnStore.getStoreType() + "-" + dpnStore.getStoreName() + "店]，订单号"
						+ order.getOrderId() ;
				if ( so != null ){
					msg = msg + "("+so.getServiceId()+")";
				}
				msg = msg + "，请于" + df.format(logisticFinalDt7.getTime()) + "前取货，谢谢！";
				smsService.sendSms(order.getReceiverMobile(), msg, order.getOrderId());
			}
			if ("order.arriveStoreRemind".equals(velocityTemplate)) {
				mail.setSubject("未取货提醒：商品已到店即将逾期，请尽速取货！");
				String msg = "您的耀点100商品已送至[达芙妮-" + dpnStore.getStoreType() + "-" + dpnStore.getStoreName() + "店]，订单号"
						+ order.getOrderId() + "，请于" + df.format(logisticFinalDt7.getTime()) + "前取货，谢谢！";
				smsService.sendSms(order.getReceiverMobile(), msg, order.getOrderId());
			}
			if ("order.arriveStoreCancel".equals(velocityTemplate)) {
				mail.setSubject("订单" + order.getOrderId() + " 逾期未至门店取货，系统已自动取消订单");

			}

			mailService.save(mail);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("order:" + order.getOrderId() + ",template:" + velocityTemplate, e);
		}
	}
	@Transactional(readOnly = false)
	public void sendNotice(String velocityTemplate, Orders order) throws CoreException {
		sendNotice(velocityTemplate,order,null);
	}
}
